package com.lyf.shop.web.controller;

import com.lyf.shop.common.Const;
import com.lyf.shop.entity.Page;
import com.lyf.shop.entity.Product;
import com.lyf.shop.services.Impl.ProductServiceImpl;
import com.lyf.shop.services.ProductService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/pro")
public class ProductController extends BaseController{
    ProductService ps = new ProductServiceImpl();

    public String getProById(HttpServletRequest request,HttpServletResponse response){
        //使用商品的主键pid来查询单个商品
        //从前端页面获取Pid
        String pid = request.getParameter("pid");
        //调动service层的方法
        Product product = ps.getProById(Integer.valueOf(pid));
        //将上面方法得到的值存入一个对象
        request.setAttribute("goods",product);
        //跳转到商品详情页面
        return Const.FORWARD+"/goodsDetail.jsp";
    }

    /**
     * 按类别查询上的数据，分页，
     * 需要使用page帮助处理分页
     * 业务提供--》查询所有数据的总行数，需要有类别的id作为条件tid
     * 分页的数据  也是需要类别id作为条件
     * @param request
     * @param response
     * @return
     * @throws ServletException
     * @throws IOException
     */
    public String getProListByTid(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取分页参数pageIndex  商品种类tid
        Integer tid = Integer.valueOf(request.getParameter("tid"));
        String pageIndex = request.getParameter("pageIndex");
        //防止当前页为空，做一个判断
        if(pageIndex==null){
            pageIndex="1";//当前页就设为1
        }
        //实例化page
        Page page = new Page(Integer.valueOf(pageIndex),4,ps.getCountByTid(tid));
        //使用page作为参数来进行分页查询
        List<Product> productList = ps.getProListByTid(tid,page);
        request.setAttribute("productList",productList);
        request.setAttribute("page",page);
        return Const.FORWARD+"/goodsList.jsp";
    }


}
